import React, { Component } from 'react';
import { getMultiLang, createPage, toast, base } from 'nc-lightapp-front';
let { NCDiv } = base;
import config from './config';
import { onPageButtonClick, onTreeSelectChange, onTableAfterChange } from './events';
import api from '../../common/api';
import { get } from 'lodash-es';

class Page extends Component {
    constructor(props) {
        super(props);
        props.use.editTable(config.bodycode);
        this.state = {
            multilang: {}
        };
    }

    componentDidMount() {
        this.initTempAndLang();
    }

    initTempAndLang() {
        const props = this.props;
        getMultiLang({
            ...config.multilang,
            callback: (json) => {
                this.setState({ multilang: json }, () => {
                    props.createUIDom({ pagecode: config.pagecode }, (data) => {
                        console.log('=====template', data);
                        this.setButton(data.button);
                        this.setMeta(data.template, data.button);
                    });
                });
            }
        });
    }

    setMeta(meta, button) {
        const props = this.props;
        // meta[config.bodycode].status = 'browse';
        // setDefData(`${config.headcode}_oid`, config.datasource, meta[config.headcode].oid);

        // meta[config.bodycode].items.push({
        //     label: this.state.multilang['opr_title'],
        //     itemtype: 'customer',
        //     attrcode: 'opr',
        //     width: '140px',
        //     visible: true,
        //     fixed: 'right',
        //     render: (text, record, index) => {
        //         const buttonArray = ['table_view'];
        //         if (record.src_type.value === '0') {
        //             if (record.billstatus.value === '0') {
        //                 buttonArray.push('table_edit', 'table_delete');
        //             } else if (record.billstatus.value === '1') {
        //                 buttonArray.push('table_edit', 'table_delete', 'table_approve');
        //             } else if (record.billstatus.value === '3') {
        //                 buttonArray.push('table_unapprove');
        //             }
        //         }

        //         return props.button.createOprationButton(buttonArray, {
        //             area: config.innerButtonArea,
        //             buttonLimit: 3,
        //             onButtonClick: (props, key) => onTableButtonClick.call(this, props, key, text, record, index)
        //         });
        //     }
        // });
        props.meta.setMeta(meta, () => {
            this.initPage();
        });
    }

    setButton(button) {
        const props = this.props;
        props.button.setButtons(button);
    }

    initPage() {
        const props = this.props;
        const params = {};

        this.setPageStatus();

        api.getObjectRegisterTree(params).then((data) => {
            // 按钮初始化
            if (!get(data, 'nodes')) {
                toast({
                    color: 'warning',
                    content: this.state.multilang['query_none_message']
                });
                return;
            }
            const tree = props.syncTree.createTreeData(data.nodes);
            props.syncTree.setSyncTreeData(config.headcode, tree);
            const root = get(tree, '[0].key')
            if (root) {
                props.syncTree.setNodeDisable(config.headcode, true, root)
            }
            // const first = get(tree, '[0].children[0].refpk');
            // if (!first) {
            //     toast({
            //         color: 'warning',
            //         content: this.state.multilang['data_wrong_message']
            //     });
            //     return;
            // }
            // props.syncTree.setNodeSelected(config.headcode, first);
            // this.loadData();
        });
    }

    setPageStatus(status = 'browse') {
        const props = this.props;
        props.setUrlParam({ status });
        if (!props.syncTree.getSelectNode(config.headcode)) {
            props.editTable.setStatus(config.bodycode, 'browse');
            props.button.setButtonVisible(['add', 'edit', 'cancel', 'save'], false);
            return
        }
        if (status === 'add') {
            props.button.setButtonVisible(['add', 'cancel', 'save'], true);
            props.button.setButtonVisible(['edit'], false);
        } else if (status === 'edit') {
            props.editTable.setStatus(config.bodycode, 'edit');
            props.button.setButtonVisible(['add', 'cancel', 'save'], true);
            props.button.setButtonVisible(['edit'], false);
        } else {
            props.editTable.setStatus(config.bodycode, 'browse');
            props.button.setButtonVisible(['add', 'edit'], true);
            props.button.setButtonVisible(['cancel', 'save'], false);
        }
    }

    loadData(node) {
        const props = this.props;
        if (!node) {
            node = props.syncTree.getSelectNode(config.headcode);
        }

        api.getObjectRegisterList({
            reportType: node.refcode
        }).then((data) => {
            const length = get(data, `${config.bodycode}.rows.length`);
            if (!length) {
                toast({
                    color: 'warning',
                    content: this.state.multilang['query_none_message']
                });
                return;
            }
            toast({
                color: 'success',
                content: this.state.multilang['query_total_message'].replace('$_$', length)
            });
            this.setData(data);
        });
    }

    setData(data) {
        const props = this.props;
        data[config.bodycode].rows.forEach((item) => {
            if (item.values.qry_objdatatype.value === '1' || !item.values.qry_objdatatype.value) {
                item.values.qry_objdatatype.value = item.values.dsp_objname.value;
                item.values.qry_objdatatype.display = item.values.dsp_objname.value;
            } else {
                item.values.qry_objdatatype.display = item.values.qry_objdatatype.value;
            }
        });
        props.editTable.setTableData(config.bodycode, data[config.bodycode]);
        this.setPageStatus();
    }

    save() {
        const props = this.props;
        props.editTable.filterEmptyRows(config.bodycode, config.tableFilterKeys);
        if (!props.editTable.checkRequired(config.bodycode, props.editTable.getAllRows(config.bodycode))) {
            return;
        }

        const reqData = props.createMasterChildDataSimple(config.pagecode, config.headcode, config.bodycode, 'editTable');
        reqData.body[config.bodycode].rows.forEach((item, i) => {
            item.values.qry_objdatatype = {
                value: props.editTable.getValByKeyAndIndex(config.bodycode, i, 'qry_objdatatype').display
            };
        });

        api.saveObjectRegister(reqData).then((data) => {
            toast({
                color: 'success',
                // content: '保存成功' this.state.multilang['']
                content: this.state.multilang['operate_success'] // 显示多语
            });
            this.setData(data);
        });
    }

    render() {
        const { editTable, button, search, modal, BillHeadInfo, syncTree, DragWidthCom } = this.props;

        return (
            <div className='nc-bill-tree-table'>
                <NCDiv areaCode={NCDiv.config.HEADER} className='header'>
                    {BillHeadInfo.createBillHeadInfo({
                        title: this.state.multilang['list_page_title'],
                        initShowBackBtn: false
                    })}
                    <div className=' btn-group'>
                        {button.createButtonApp({
                            area: config.pageButtonArea,
                            buttonLimit: 8,
                            onButtonClick: onPageButtonClick.bind(this)
                        })}
                    </div>
                </NCDiv>
                <div className='tree-table'>
                    <DragWidthCom
                        leftDom={
                            <NCDiv fieldid='sysparam' areaCode={NCDiv.config.TREE} className='tree-area'>
                                {syncTree.createSyncTree({
                                    treeId: config.headcode, // 组件id
                                    needSearch: true, //是否需要查询框，默认为true,显示。false: 不显示
                                    needEdit: false, //是否需要编辑节点功能，默认为true,可编辑；false：不可编辑
                                    // editNodeCallBack: this.editNodeCallBack.bind(this),//编辑节点回调方法
                                    // addNodeCallBack: this.addNodeCallBack.bind(this),//  新增节点回调方法
                                    // delNodeCallBack: this.delNodeCallBack.bind(this),//删除节点回调方法
                                    // onSelectEve: this.onSelectEve.bind(this) //选择节点回调方法
                                    onSelectedChange: onTreeSelectChange.bind(this), //监听选择节点改变事件
                                    // userDefine:this.defineEve.bind(this) // 业务组自定义dom事件,布局放在树最上面
                                    // onTreeStatusChange:this.treeStatusChange.bind(this),  //树 编辑态改变监听事件
                                    // showLine :false,  //是否显示连线，默认不显示
                                    defaultExpandAll: true //默认展开所有节点
                                    // onMouseEnterEve:this.onMouseEnterEve.bind(this), //鼠标滑过节点事件
                                    // showModal:false ,                               //是否使用弹出式编辑
                                    // clickEditIconEve: this.clickEditIconEve.bind(this), //编辑点击 回调
                                    // clickAddIconEve: this.clickAddIconEve.bind(this), //新增点击 回调
                                    // clickDelIconEve: this.clickDelIconEve.bind(this), // 删除点击 回调
                                    // showModal:false,  //是否使用弹出式编辑
                                    // metaId:'',        // 弹出框中内容，树模板id（需要弹出编辑框才使用）
                                    // searchType:'location',   // 搜索框查询方式，定位/过滤  location/filtration，默认定位
                                    // openIcon:this.openIcon,  // 展开状态图标替换 ( 业务组自定义展开和关闭图标时，需要根据全局变量NODE_ENV，填加field = 'tree-switcher' ,fieldname='树开关' ，用于自动化测试)
                                    // closeIcon：this.closeIcon, // 关闭状态图标替换，参考展开
                                    // onTreeExpand: this.onTreeExpand.bind(this) //展开树节点事件
                                    // disabledSearch: true //是否显示搜索框
                                    // hiddenDefaultIcon : true, //隐藏默认的文件夹图标
                                    // getSearchVal : this.getSearchVal.bind(this) //获取搜索框值
                                })}
                            </NCDiv>
                        }
                        rightDom={
                            <div style={{ height: '100%' }}>
                                <div className='nc-single-table'>
                                {editTable.createEditTable(config.bodycode, {
                                    // handlePageInfoChange: onTablePageChange.bind(this),
                                    // onRowDoubleClick: onTableRowDoubleClick.bind(this),
                                    // selectedChange: onTableSelectChange.bind(this),
                                    onAfterEvent: onTableAfterChange.bind(this),
                                    dataSource: config.datasource,
                                    showIndex: true,
                                    showCheck: false,
                                    adaptionHeight: true
                                })}
                                </div>
                            </div>
                        }
                        defLeftWid='280px'
                    />
                </div>
            </div>
        );
    }
}

export default createPage({
    // billinfo: {
    //     billtype: 'grid',
    //     pagecode: config.pagecode,
    //     headcode: config.headcode
    // },
    mutiLangCode: config.mutiLangCode,
    initTemplate: null
})(Page);
